package com.loujianwei.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;

import com.loujianwei.dao.UserDao;
import com.loujianwei.domain.User;
import com.loujianwei.domain.UserRole;

public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {

	// 如果只是修改了，方法体中的内容，是可以不用重启tomcat的。如果是添加了方法则是需要修改的。
	@Override
	public List<User> findUserByAccountAndId(String userId, String account) {
		String hql = "FROM User WHERE account = ?";
		if(StringUtils.isNotBlank(userId)){
			hql += " AND id != ?"; // 排除id等于当前传过来的数据
		}
		Query query = getSession().createQuery(hql);
		query.setParameter(0, account);
		if(StringUtils.isNotBlank(userId)){
			query.setParameter(1, userId);
		}
		return query.list();
	}
	@Override
	public void saveUserRole(UserRole userRole) {
		getHibernateTemplate().save(userRole);
	}

	@Override
	public void deleteUserRoleByUserId(String id) {
		Query query = getSession().createQuery("DELETE FROM UserRole WHERE id.userId=?");
		query.setParameter(0, id);
		query.executeUpdate();
	}

	@Override
	public List<UserRole> getUserRolesByUserId(String id) {
		Query query = getSession().createQuery("FROM UserRole WHERE id.userId=?");
		query.setParameter(0, id);
		return query.list();
	}
	@Override
	public List<User> findUsersByAcccountAndPass(String account, String password) {
		Query query = getSession().createQuery("FROM User WHERE account=? AND password=?");
		query.setParameter(0, account);
		query.setParameter(1, password);
		return query.list();
	}
}
